# @Time : 2020/10/19 16:25
# @Author : Fioman 
# @Phone : 13149920693
import queue
import socket
import threading
import gevent
import win32api
import settings

from tools.my_logger import *
from tools.db_handler import DB_handler
from hd_socket.parse_xml import *


class HdClient(object):
    def __init__(self, serverIp, port, logger, db, msgQ):
        """
        初始化HdClient对象
        :param serverIp:服务器IP地址
        :param port: 连接端口
        :param logger: 日志对象
        :param db: 数据库对象
        :param msgQ:发送给前端的消息
        """
        self.deviceName = "HD001"
        self.logger = logger
        self.db = db
        self.addr = (serverIp, port)
        self.msgQ = msgQ
        self.errorMsg = None
        socket.setdefaulttimeout(5)
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.settimeout(5)  # 5秒之后还没有应答或者接受到数据,就认为是失败的.
        self.modify_buffer_size(self.sock)  # 更改发送和接收的缓存区的大小

        self.sendAskFlag = False  # 设备间隔去发送请求,EAP是否存在
        self.eapReply = False  # eap是否回复了设备的ask请求你在吗的请求
        self.eapOnline = False  # eap是否在线
        self.deviceInfoChange = False  # 操作模式发生改变的时候为True
        self.equipmentStatusChange = False  # 设备的运行,停机状态发生改变
        self.alarmReportFlag = False # 报警上报标志
        self.recipeModifyFlag = False  # 配方参数发生变化标志,需要上报配方参数信息
        self.processDataReportFlag = False # 制程资料上报
        self.userLoginReportFlag = True # 上下岗报告
        
        
        try:
            data = self.db._get_data(self.db.params_db, "device_info")[1][0]
            self.ask_duration = int(data.get('ask_duration'), 60)  # 想EAP发送你在吗的时间间隔
            self.datetime_duration = int(data.get('datetime_duration'), 60)
            self.operation_mode = data.get('operation_mode')  # 操作模式
            self.total_count_duration = data.get('total_count_duration')
            self.equipment_status = data.get('equipment_status', "1")
        except Exception as e:
            self.logger.debug('数据库操作异常..{}'.format(str(e)))
            self.ask_duration = 60
            self.datetime_duration = 60
            self.operation_mode = "1"
            self.total_count_duration = 2
        try:
            self.sock.connect(self.addr)
        except Exception as e:
            print('连接失败')
            self.logger.debug('和EC系统连接失败,请检查网络是否接通..' + str(e))
            self.error_msg = '和EC系统连接失败,请检查网络是否接通..'
        time.sleep(3) # 延时3秒再发送消息
        self.recv_thread = threading.Thread(target=self.recv_msg, name='recv_thread')
        self.send_thread = threading.Thread(target=self.send_msg, name='send_thread')
        self.manager_thread = threading.Thread(target=self.manager, name='manager_thread')

    def modify_buffer_size(self, hdSock):
        # 获取当前套接字关联的选项,socket.SOL_SOCKET,正在使用的socket,socket.SOCK_STREAM发送缓存区的大小
        bsize_send = hdSock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
        bsize_recv = hdSock.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)
        print('Buffer size [Before]:{},{}'.format(bsize_send, bsize_recv))

        # 设置TCP套接字关联的选项
        # socket.TCP_NODELAY TCP层套接口选项
        # socket.TCP_NODELAY.表示禁用了Nagle,允许小包发送.不用等很多的包折合一起再发送的问题.适用于数据量小的项目.
        hdSock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)

        # 设置发送缓存区套接字关联的选项
        hdSock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, settings.BUFFER_SIZE)
        # 设置接收缓存区套接字关联的选项
        hdSock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, settings.BUFFER_SIZE)
        bsize_send = hdSock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
        bsize_recv = hdSock.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)
        print('Buffer size [After]:{},{}'.format(bsize_send, bsize_recv))

    def server_reply_listen(self):
        start = time.time()
        while time.time() - start < self.ask_duration - 5:
            if self.eapReply:
                print("检测到了EAP系统的回复...")
                self.eapOnline = True
                break
            gevent.sleep(0.05)
        else:
            print("{} 时间范围内没有收到EAP设备的回复,设备不在线..".format(self.ask_duration - 5))
            self.eapOnline = False

    def send_datetime_timer(self):
        msgName, data = self.get_current_date_data()
        self.send_msg_to_eap(msgName, data)  # 定时去发送这个消息
        self.hdDatetimeTimer = threading.Timer(self.datetime_duration * 60, self.send_datetime_timer)
        self.hdDatetimeTimer.start()

    def send_ask_timer(self):
        """
        定时发送是否在线任务,时间间隔默认是60秒.self.duration. 使用一个定时器,没过多少时间去执行一次这个任务
        :return:
        """
        self.sendAskFlag = True
        self.hdAskTimer = threading.Timer(self.ask_duration, self.send_ask_timer)
        self.hdAskTimer.start()

    def send_total_count_timer(self):
        """
        定时发送产品数量任务,时间间隔是self.total_count_duration
        :return:
        """
        msgName, data = self.get_total_count_data()
        self.send_msg_to_eap(msgName, data)
        data = self.sock.recv(settings.BUFFER_SIZE)
        if len(data) <= 0:
            print("消息{} 没有收到回复,通信异常或者设备不在线".format(msgName))
        else:
            msgNameRet, bodyDict, retCode = parse_recv_msg(data)
            print("消息{} 收到了回复,回复内容:msgName = {},bodyDict = {},retCode = {}".format(msgName, msgNameRet, bodyDict, retCode))
        self.hdTotalCountTimer = threading.Timer(self.total_count_duration, self.send_total_count_timer)
        self.hdTotalCountTimer.start()

    def manager(self):
        # 调用定时器,间隔一段时间一直向服务器发送"Are you there reply 的包"
        # self.send_ask_timer()
        # self.send_datetime_timer()
        # self.send_total_count_timer()
        while True:
            if settings.IS_MAIN_ALIVE:
                try:
                    if not self.recv_thread.is_alive():
                        self.recv_thread = threading.Thread(target=self.recv_msg, name="recv_thread")
                        self.recv_thread.setDaemon(True)
                        self.recv_thread.start()

                    if not self.send_thread.is_alive():
                        self.send_thread = threading.Thread(target=self.send_msg, name='send_thread')
                        self.send_thread.setDaemon(True)
                        self.send_thread.start()
                except Exception as e:
                    print("Manager Error:{}".format(str(e)))
                    self.logger.debug('Manager Error:{}'.format(str(e)))
            else:
                self.hdAskTimer.cancel()  # 主线程结束,取消定时任务
                self.hdDatetimeTimer.cancel()  # 取消发送时间的定时任务
                self.sock.close()

            gevent.sleep(0.05)

    def recv_msg(self):
        """
        接收消息的线程,处理接收到的消息
        :return:
        """
        while True:
            if not self.sock:
                break
            try:
                recvData = self.sock.recv(settings.BUFFER_SIZE)
                if recvData:
                    # 这里要加一个判断,判断开始和结尾的字符是什么.
                    recvMsg = recvData
                    msgName, bodyDict, retCode = parse_recv_msg(recvMsg)
                    print("从EAP接收到消息: msgName = {},bodyDict = {},retCode = {}".format(msgName, bodyDict, retCode))
                    # 返回的是成功码,就去处理这个消息.如果返回的是错误码.就不去做处理
                    if retCode == "0":
                        self.deal_recv_msg(msgName, bodyDict)
                    else:
                        gevent.sleep(0.05)
            except Exception as e:
                continue
            else:
                gevent.sleep(0.05)

    def send_msg_to_eap(self, msgName, data):
        """
        向eap发送消息,注意发送消息的时候,要加上消息头和消息结尾
        :param data: xml消息的字节二进制格式
        :return:
        """
        msgSend = bytes(chr(2), encoding="ascii") + data + bytes(chr(3), encoding="ascii")
        print("发送消息到EAP: {}".format(msgName))  # 这里最好是解析出来消息的类型.也就是发送消息的名称,内容都解析出来.
        try:
            self.sock.sendall(msgSend)
        except Exception as e:
            print("in send_msg_to_eap(),self.sock.sendall() 出现异常: {}".format(str(e)))
            self.logger.debug("in send_msg_to_eap(),self.sock.sendall() 出现异常: {}".format(str(e)))
            return False
        return True

    def send_msg(self):
        while True:
            if not self.sock:
                break

            if self.sendAskFlag:
                msgName, data = self.get_ask_msg_data()
                res = self.send_msg_to_eap(msgName, data)
                if res:  # 如果发送成功,这个时候要打开一个定时器
                    self.sendAskFlag = False
                    self.eapReply = False
                    # 创建一个执行50秒的函数,去执行一个监听函数,看看有没有收到设备的回复.如果没有收到就证明EAP系统是不在线的.
                    eapOnlineListener = threading.Thread(target=self.server_reply_listen)
                    eapOnlineListener.setDaemon(True)
                    eapOnlineListener.start()

            if self.deviceInfoChange:
                msgName, data = self.get_device_basic_info()
                res = self.send_msg_to_eap(msgName, data)
                if res:  # 如果发送成功
                    self.deviceInfoChange = False
                    data = self.sock.recv(settings.BUFFER_SIZE)
                    if len(data) <= 0:
                        print("消息 {}没有收到回复".format(msgName))
                    else:
                        msgNameRet, bodyDict, retCode = parse_recv_msg(data)
                        print("消息 {}收到了回复,回复的消息类型:{},内容:{},结果码:{}".format(msgName, msgNameRet, bodyDict, retCode))

            if self.equipmentStatusChange:
                msgName, data = self.get_equipment_status_data()
                res = self.send_msg_to_eap(msgName, data)
                if res:
                    self.equipmentStatusChange = False
                    data = self.sock.recv(settings.BUFFER_SIZE)
                    if data <= 0:
                        print("消息 {} 没有收到回复".format(msgName))
                    else:
                        msgNameRet, bodyDict, retCode = parse_recv_msg(data)
                        print("消息 {}收到了回复,回复的消息类型:{},内容:{},结果码:{}".format(msgName, msgNameRet, bodyDict, retCode))

            if self.alarmReportFlag:
                msgName, data = self.get_alarm_warning_report_data()
                res = self.send_msg_to_eap(msgName, data)
                if res:
                    data = self.sock.recv(settings.BUFFER_SIZE)
                    if len(data) <= 0:
                        print("消息 {} 没有收到回复".format(msgName))
                    else:
                        msgNameRet, bodyDict, retCode = parse_recv_msg(data)
                        print("消息 {}收到了回复,回复的消息类型:{},内容:{},结果码:{}".format(msgName, msgNameRet, bodyDict, retCode))
                        self.alarmReportFlag = False

            if self.recipeModifyFlag:
                msgName, data = self.get_recipe_modify_report_data()
                res = self.send_msg_to_eap(msgName, data)
                if res:
                    data = self.sock.recv(settings.BUFFER_SIZE)
                    if len(data) <= 0:
                        print("消息 {} 没有收到回复".format(msgName))
                    else:
                        msgNameRet, bodyDict, retCode = parse_recv_msg(data)
                        print("消息 {}收到了回复,回复的消息类型:{},内容:{},结果码:{}".format(msgName, msgNameRet, bodyDict, retCode))
                        self.recipeModifyFlag = False

            if self.processDataReportFlag:
                # 制程资料上报
                msgName,data = self.get_process_report_data()
                res = self.send_msg_to_eap(msgName, data)
                if res:
                    data = self.sock.recv(settings.BUFFER_SIZE)
                    if len(data) <= 0:
                        print("消息 {} 没有收到回复".format(msgName))
                    else:
                        msgNameRet, bodyDict, retCode = parse_recv_msg(data)
                        print("消息 {}收到了回复,回复的消息类型:{},内容:{},结果码:{}".format(msgName, msgNameRet, bodyDict, retCode))
                        self.processDataReportFlag = False

            if self.processDataReportFlag:
                # 制程资料上报,judge 默认是1，制程id改成时间。
                msgName,data = self.get_process_report_data()
                res = self.send_msg_to_eap(msgName, data)
                if res:
                    data = self.sock.recv(settings.BUFFER_SIZE)
                    if len(data) <= 0:
                        print("消息 {} 没有收到回复".format(msgName))
                    else:
                        msgNameRet, bodyDict, retCode = parse_recv_msg(data)
                        print("消息 {}收到了回复,回复的消息类型:{},内容:{},结果码:{}".format(msgName, msgNameRet, bodyDict, retCode))
                        self.processDataReportFlag = False
            
            if self.userLoginReportFlag:
                # 制程资料上报,judge 默认是1，制程id改成时间。
                msgName,data = self.user_login_report_data()
                res = self.send_msg_to_eap(msgName, data)
                if res:
                    data = self.sock.recv(settings.BUFFER_SIZE)
                    if len(data) <= 0:
                        print("消息 {} 没有收到回复".format(msgName))
                    else:
                        msgNameRet, bodyDict, retCode = parse_recv_msg(data)
                        print("消息 {}收到了回复,回复的消息类型:{},内容:{},结果码:{}".format(msgName, msgNameRet, bodyDict, retCode))
                        self.userLoginReportFlag = False
            

    def deal_recv_msg(self, msgType, bodyDict):
        """
        处理接收到的消息
        :param msgName: 接收到的消息类型
        :param bodyDict: 接收到消息的body内容
        :return:
        """
        if msgType == "Are You There Reply":
            self.eapReply = True  # 将EAP回复设置为True
        elif msgType == "Initial Data Request":
            # 1. 先获取要回复的数据,然后就是发送回复
            msgName, initialReplyData = self.get_initial_data_reply()
            self.send_msg_to_eap(msgName, initialReplyData)
        elif msgType == "Trace Data Request":
            # 设备收到点检数据请求
            msgName, traceRequestData = self.get_trace_reply_data()
            # 2. 点检数据恢复
            self.send_msg_to_eap(msgName, traceRequestData)
        elif msgType == "Date Time Sync Command":
            # 日期时间校时命令
            msgName, DateTimeSyncData = self.get_datetime_sync_data()
            # 回复收到时间校准命令,并进行时间矫正
            serviceTime = bodyDict["date_time"]
            self.sync_sys_time(serviceTime)
            self.send_msg_to_eap(msgName, DateTimeSyncData)
        elif msgType == "CIM Message Command":
            # 远程讯息命令,获取命令的种类,命令的时间间隔,消息的内容
            actionType = bodyDict["action_type"]  # 消息类别
            intervalSecondTime = bodyDict["interval_second_time"]  # 间隔秒数,间隔消息时使用
            cimMessage = bodyDict["cim_message"]  # 远程消息的内容
            print("收到远程讯息命令:,action_type = {},interval_second_time = {},cim_message = {}".format(actionType, intervalSecondTime, cimMessage))
            msgName, cimMessageReplyData = self.get_cim_message_reply_data()
            self.send_msg_to_eap(msgName, cimMessageReplyData)

        elif msgType == "Recipe Name Exist Request":
            # 询问配方是否存在
            recipeName = bodyDict["recipe_name"]
            data = self.db._get_data(self.db.params_db, "device_info")[1][0]
            recipeNameList = data.get("recipe_name_list",["recipe_001","recipe_002","recipeName01"])

            if recipeName not in recipeNameList:
                recipeName = ""

            msgName,recipeExistReplyData = self.get_recipe_exist_reply_data(recipeName)
            self.send_msg_to_eap(msgName,recipeExistReplyData)

        elif msgType == "Recipe Body Request":
            # EAP以配方名称询问设备配方参数的详细内容
            recipeName = bodyDict["recipe_name"]
            data = self.db._get_data(self.db.params_db,"device_info")[1][0]
            recipeBodyTestData = [recipeName,[("width","600"),("height","600")]]
            msgName,recipeBodyReplyData = self.get_recipe_body_reply_data(recipeBodyTestData)
            self.send_msg_to_eap(msgName,recipeBodyReplyData)
        elif msgType == "Recipe Name Change Request":
            # EAP 配方切换= 可以切换，不可以切换
            recipeName  = bodyDict["recipe_name"]
            changeAllowed = False
            msgName,recipeChangeReplyData = self.get_recipe_change_reply_data(changeAllowed)
            self.send_msg_to_eap(msgName,recipeChangeReplyData)


    def sync_sys_time(self, serviceTime):
        """
        根据服务器发过来的时间,进行时间校准
        :param serviceTime:
        :return:
        """
        year = int(serviceTime[:4])
        month = int(serviceTime[4:6])
        day = int(serviceTime[6:8])
        hour = int(serviceTime[8:10])
        min = int(serviceTime[10:12])
        sec = int(serviceTime[12:])
        win32api.SetSystemTime(year, month, day, day, hour, min, sec, 0)

    def get_initial_data_reply(self):
        """
        获取发送给初始化数据请求的二进制格式数据
        :return:
        """
        msgName = "Initial Data Reply"
        operationMode, totalWipCount, equipmentStatus, recipName = self.db.get_initial_data()
        bodyDict = {"date_time": get_transaction_id()[:-3],
                    "operation_mode": operationMode,
                    "total_wip_count": totalWipCount,
                    "equipment_status": equipmentStatus,
                    "recipe_name": recipName}
        retDict = {"returncode": '0',
                   "returnmessage": ''}
        pack_send_msg(msgName, bodyDict, retDict)
        with open(r"./send_msg.xml", "rb") as f:
            data = f.read()
        return msgName, data

    def get_ask_msg_data(self):
        """
        获取发送请求设备是否存在的请求的数据内容
        :return:
        """
        # 1. 首先是将要发送的消息写入到ask_msg
        msgName = "Are You There Request"
        bodyDict = {"user_id": self.deviceName,
                    "service_ip": settings.SERVICE_IP}
        retDict = {"returncode": '0',
                   "returnmessage": ''}
        pack_send_msg(msgName, bodyDict, retDict)

        # 2. 然后是读取文件发送这个消息
        with open(r'./ask_msg.xml', 'rb') as f:
            data = f.read()
        return msgName, data

    def get_current_date_data(self):
        """获取发送到EAP的设备时间的数据"""
        msgName = "Equipment Current Date Time"
        bodyDict = {"date_time": get_transaction_id()[:-3]}
        retDict = {"returncode": "0", "returnmessage": ""}
        pack_send_msg(msgName, bodyDict, retDict)
        with open(r"./send_msg.xml", "rb") as f:
            data = f.read()
        return msgName, data

    def get_device_basic_info(self):
        """
        获取设备的基本信息数据
        :return:
        """
        msgName = "Equipment Information"
        operationMode, totalWipCount, equipmentStatus, recipName = self.db.get_initial_data()
        bodyDict = {
            "operation_mode": operationMode,
            "recipe_name": recipName
        }
        retDict = {
            "returncode": "0",
            "returnmessage": ""
        }
        pack_send_msg(msgName, bodyDict, retDict)
        with open(r"./send_msg.xml", "rb") as f:
            data = f.read()
        return msgName, data

    def get_total_count_data(self):
        msgName = "Equipment Total Count"
        data = self.db._get_data(self.db.params_db, "device_info")[1][0]
        totalWipCount = data.get("total_wip_count", "0")
        bodyDict = {
            "total_wip_count": totalWipCount,
        }
        retDict = {
            "returncode": "0",
            "returnmessage": ""
        }
        pack_send_msg(msgName, bodyDict, retDict)
        with open(r"./send_msg.xml", "rb") as f:
            data = f.read()
        return msgName, data

    def get_equipment_status_data(self):
        msgName = "Equipment Status"
        data = self.db._get_data(self.db.params_db, "device_info")[1][0]
        equipmentStatus = data.get("equipment_status", "1")
        bodyDict = {
            "equipment_status": equipmentStatus,
        }
        retDict = {
            "returncode": "0",
            "returnmessage": ""
        }
        pack_send_msg(msgName, bodyDict, retDict)
        with open(r"./send_msg.xml", "rb") as f:
            data = f.read()
        return msgName, data

    def get_alarm_warning_report_data(self):
        msgName = "Alarm Warning Data Report"
        data = self.db._get_data(self.db.params_db, "device_info")[1][0]
        alarmType = data.get("alarm_type", "S")
        reportType = data.get('report_type', "S")
        awCode = data.get('aw_code', "Device Alarm")
        awText = data.get('aw_text', "Connect Errror! Device rs stop")
        bodyDict = {
            "alarm_type": alarmType,
            "report_type": reportType,
            "aw_code": awCode,
            "aw_text": awText
        }
        retDict = {
            "returncode": "0",
            "returnmessage": ""
        }
        pack_send_msg(msgName, bodyDict, retDict)
        with open(r"./send_msg.xml", "rb") as f:
            data = f.read()
        return msgName, data

    def get_trace_reply_data(self):
        msgName = "Trace Data Reply"
        traceDataList = [
            ("1", "KnifeUsed", "1000"),
            ("2", "TableUsed", "1.3"),
            ("3", "Temperature", "38")
        ]
        retDict = {
            "returncode": "0",
            "returnmessage": ""
        }
        pack_send_msg(msgName, traceDataList, retDict)
        with open(r"./send_msg.xml", "rb") as f:
            data = f.read()
        return msgName, data

    def get_recipe_modify_report_data(self):
        """
        获取配方发生变化时上报的信息
        :return:
        """
        msgName = "Recipe Body Modify Report"
        data = self.db._get_data(self.db.params_db, "device_info")[1][0]
        modifyType = data.get("modify_type", "1")
        modifyRecipeName = data.get("recipe_name", "test_modify_12345")
        bodyDict = {
            "modify_type": modifyType,
            "recipe_name": modifyRecipeName
        }
        retDict = {
            "returncode": "0",
            "returnmessage": ""
        }
        pack_send_msg(msgName, bodyDict, retDict)
        with open(r"./send_msg.xml", "rb") as f:
            data = f.read()
        return msgName, data

    def get_datetime_sync_data(self):
        """
        回复给eap收到时间校准命令的数据
        :return:
        """
        msgName = "Date Time Sync Reply"
        bodyDict = {}
        retDict = {
            "returncode": "0",
            "returnmessage": ""
        }
        pack_send_msg(msgName, bodyDict, retDict)
        with open(r"./send_msg.xml", "rb") as f:
            data = f.read()
        return msgName, data


    def get_cim_message_reply_data(self):
        """
        回复给eap收到远程讯息命令
        :return:
        """
        msgName = "CIM Message Command Reply"
        bodyDict = {}
        retDict = {
            "returncode": "0",
            "returnmessage": ""
        }
        pack_send_msg(msgName, bodyDict, retDict)
        with open(r"./send_msg.xml", "rb") as f:
            data = f.read()
        return msgName, data


    def get_recipe_exist_reply_data(self,recipeName):
        msgName = "Recipe Name Exist Reply"
        if recipeName == "":
            retDict = {
                "returncode": "-1",
                "returnmessage": "Recipe Name Not Exist!"
            }
        else:
            retDict = {
                "returncode": "0",
                "returnmessage": ""
            }
        bodyDict = {
            "recipe_name":recipeName
        }

        pack_send_msg(msgName, bodyDict, retDict)
        with open(r"./send_msg.xml", "rb") as f:
            data = f.read()
        return msgName, data

    def get_recipe_body_reply_data(self,recipeBody):
        msgName = "Recipe Body Reply"
        bodyDict = recipeBody
        retDict = {
            "returncode": "0",
            "returnmessage": ""
        }
        pack_send_msg(msgName,bodyDict,retDict)
        with open(r"./send_msg.xml", "rb") as f:
            data = f.read()
        return msgName, data

    def get_recipe_change_reply_data(self,changeAllowed):
        msgName = "Recipe Name Change Reply"
        bodyDict = {}
        if changeAllowed:
            retDict = {
                "returncode": "0",
                "returnmessage": ""
            }
        else:
            retDict = {
                "returncode": "-2",
                "returnmessage": "Device Busy!"
            }
        pack_send_msg(msgName, bodyDict, retDict)
        with open(r"./send_msg.xml", "rb") as f:
            data = f.read()
        return msgName, data

    def get_process_report_data(self):
        msgName = "Process Data Report"
        bodyDict = ["1","1",get_transaction_id(),[("width","300"),("height","400")]]
        retDict = {
            "returncode": "0",
            "returnmessage": ""
        }
        pack_send_msg(msgName, bodyDict, retDict)
        with open(r"./send_msg.xml", "rb") as f:
            data = f.read()
        return msgName, data

    def user_login_report_data(self):
        msgName = "User Login Logout Report"
        bodyDict = {
            "work_type":"2",
            "user_no":"123"
        }
        retDict = {
            "returncode": "0",
            "returnmessage": ""
        }
        pack_send_msg(msgName, bodyDict, retDict)
        with open(r"./send_msg.xml", "rb") as f:
            data = f.read()
        return msgName, data
if __name__ == '__main__':
    logger = log_init(__name__)
    db = DB_handler()
    msgQueue = queue.Queue()  # 消息队列
    client = HdClient(settings.SERVICE_IP, settings.PORT, logger, db, msgQueue)
    # msgNameRet, data = client.get_ask_msg_data()
    # print("msgName:{}".format(msgNameRet))
    # msgNameRet, data = client.get_initial_data_reply()
    # print("msgName:{}".format(msgNameRet))
    # msgNameRet, data = client.get_device_basic_info()
    # print("msgName:{}".format(msgNameRet))
    # msgNameRet, data = client.get_total_count_data()
    # print("msgName:{}".format(msgNameRet))
    # msgNameRet, data = client.get_alarm_warning_report_data()
    # print("msgName:{}".format(msgNameRet))
    # msgNameRet, data = client.get_trace_reply_data()
    # print("msgName:{}".format(msgNameRet))
    # msgNameRet, data = client.get_datetime_sync_data()
    # print("msgName:{}".format(msgNameRet))
    # msgNameRet, data = client.get_cim_message_reply_data()
    # print("msgName:{}".format(msgNameRet))

    settings.IS_MAIN_ALIVE = True
    client.manager_thread.setDaemon(True)
    client.manager_thread.start()
    while True:
        settings.IS_MAIN_ALIVE = True
        gevent.sleep(1)
